package com.innovation.chengzhangriji.ui;

import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;

import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.ui.widget.CameraPreview;
import com.innovation.chengzhangriji.ui.widget.CuteImageView;
import com.innovation.chengzhangriji.ui.widget.ThumbnailAdapter;
import com.innovation.chengzhangriji.util.FileUtils;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class TimelineCameraActivity extends BaseTimelinePhotoAndCameraActivity implements View.OnClickListener, Camera.PictureCallback, ThumbnailAdapter.OnClickAdapterListener {

    private static final String TAG = TimelineCameraActivity.class.getSimpleName();

    private Camera mCamera;

    private ThumbnailAdapter adapter;

    private boolean safeToTakePicture = false;

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_timeline_camera);
        RecyclerView view = (RecyclerView) findViewById(R.id.recycler_thumbnail);
        GridLayoutManager themesGridLayoutManager = new GridLayoutManager(this, 1, LinearLayoutManager.VERTICAL, false);
        view.setLayoutManager(themesGridLayoutManager);
        adapter = new ThumbnailAdapter();
        adapter.setOnClickAdapterListener(this);
        view.setAdapter(adapter);
        CuteImageView button = (CuteImageView) findViewById(R.id.button_camera);
        button.setOnClickListener(TimelineCameraActivity.this);
        new initCameraTask().execute();
    }

    @Override
    protected String[] getTimelineUrls() {
        return adapter.getThumbnailUrlArray();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        releaseCamera();
    }

    @Override
    public void onClick(View v) {
        if (adapter.getThumbnailLength() < 9) {
            if (safeToTakePicture) {
                addPhoto();
                mCamera.takePicture(null, null, this);
                safeToTakePicture = false;
            }
        }
    }

    @Override
    protected void onPageStart() {
        MobclickAgent.onPageStart(Config.UMENG_PAGE_TIMELINE_CAMERA);
    }

    @Override
    protected void onPageEnd() {
        MobclickAgent.onPageEnd(Config.UMENG_PAGE_TIMELINE_CAMERA);
    }

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
        new createPictureTask(camera).execute(data);
    }

    @Override
    public void onClickThumbnail(String url) {

    }

    @Override
    public void onClickDelete(String url) {
        FileUtils.deleteFile(url);
        removePhoto();
    }

    private void releaseCamera() {
        if (mCamera != null) {
            mCamera.release();        // release the camera for other applications
            mCamera = null;
        }
    }

    private void galleryAddPic(File f) {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        this.sendBroadcast(mediaScanIntent);
    }

    private void resultPath(String path) {
        adapter.addThumbnail(path);
        mCamera.startPreview();
        /*Intent resultIntent = new Intent();
        resultIntent.putExtra(Config.ACTION_EXTERNAL_RESULT_PHOTO, path);
        setResult(RESULT_OK, resultIntent);
        finish();*/
    }

    private int mRotate = 90;

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mRotate = 0;
        } else {
            mRotate = 90;
        }
    }

    private class initCameraTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            mCamera = CameraHelper.getDefaultCameraInstance();
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            if(mCamera == null) {
                tipShow("打开相机失败");
                finish();
                return;
            }
            CameraPreview cameraPreview = new CameraPreview(TimelineCameraActivity.this, mCamera);
            FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
            preview.addView(cameraPreview);
            safeToTakePicture = true;
        }
    }

    private class createPictureTask extends AsyncTask<byte[], Void, File> {

        BitmapFactory.Options opt;

        public createPictureTask(Camera camera) {
            // 解决 out of memory
            opt = new BitmapFactory.Options();
            opt.inTempStorage = new byte[16 * 1024];
            Camera.Parameters parameters = camera.getParameters();
            Camera.Size size = parameters.getPictureSize();

            int height11 = size.height;
            int width11 = size.width;
            float mb = (width11 * height11) / 1024000;

            if (mb > 4f)
                opt.inSampleSize = 4;
            else if (mb > 3f)
                opt.inSampleSize = 2;
        }

        @Override
        protected File doInBackground(byte[]... data) {
            File pictureFile = Config.createPicture();
            if (pictureFile == null) {
                return null;
            }
            Bitmap bm = null, rotatedBitmap = null;
            try {
                bm = BitmapFactory.decodeByteArray(data[0], 0, data[0].length,opt);
                Matrix matrix = new Matrix();
                matrix.postRotate(mRotate);
                rotatedBitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
                FileOutputStream fos = new FileOutputStream(pictureFile);
                rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                fos.flush();
                fos.close();
            } catch (FileNotFoundException e) {
                Log.d(TAG, "File not found: " + e.getMessage());
            } catch (IOException e) {
                Log.d(TAG, "Error accessing file: " + e.getMessage());
            } finally {
                if(bm != null && !bm.isRecycled()) {
                    bm.recycle();
                }
                bm = null;
                if(rotatedBitmap != null && !rotatedBitmap.isRecycled()) {
                    rotatedBitmap.recycle();
                }
                rotatedBitmap = null;
            }
            return pictureFile;
        }

        @Override
        protected void onPostExecute(File pictureFile) {
            super.onPostExecute(pictureFile);
            galleryAddPic(pictureFile);
            resultPath(pictureFile.getPath());
            safeToTakePicture = true;
        }
    }
}